// 本地存储工具函数

/**
 * 清除所有本地数据
 */
export const clearAllStorage = () => {
  localStorage.removeItem('3d-platform-storage')
  sessionStorage.clear()
  console.log('✅ 所有本地数据已清除')
}

/**
 * 导出订单数据
 */
export const exportOrders = (orders) => {
  const data = JSON.stringify(orders, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  
  const a = document.createElement('a')
  a.href = url
  a.download = `orders_${new Date().toISOString().split('T')[0]}.json`
  a.click()
  
  URL.revokeObjectURL(url)
  console.log('✅ 订单数据已导出')
}

/**
 * 导入订单数据
 */
export const importOrders = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target.result)
        resolve(data)
        console.log('✅ 订单数据已导入')
      } catch (error) {
        reject(new Error('数据格式错误'))
      }
    }
    
    reader.onerror = () => reject(new Error('文件读取失败'))
    reader.readAsText(file)
  })
}

/**
 * 获取存储大小
 */
export const getStorageSize = () => {
  let total = 0
  for (let key in localStorage) {
    if (localStorage.hasOwnProperty(key)) {
      total += localStorage[key].length + key.length
    }
  }
  
  return {
    bytes: total,
    kb: (total / 1024).toFixed(2),
    mb: (total / 1024 / 1024).toFixed(2)
  }
}

/**
 * 检查存储空间
 */
export const checkStorageQuota = () => {
  const size = getStorageSize()
  const maxSize = 5 * 1024 * 1024 // 5MB 限制
  const usagePercent = ((size.bytes / maxSize) * 100).toFixed(2)
  
  return {
    ...size,
    usagePercent,
    available: size.bytes < maxSize
  }
}

